<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script >
        // 获取选择文件表单
        var filechooser = document.getElementById("choose");
        // 点击上传
        $("#upload").on("click", function() {
            filechooser.click();
        })
            .on("touchstart", function() {
                $(this).addClass("touch")
            })
            .on("touchend", function() {
                $(this).removeClass("touch")
            });
       //
        function changeImage() {
            if (!this.files.length) return;
            var files = Array.prototype.slice.call(this.files);
            if (files.length > 9) {
                alert("最多同时只可上传9张图片");
                return;
            }
            files.forEach(function(file, i) {
                if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
                var reader = new FileReader();
                var li = document.createElement("li");
                //   获取图片大小
                var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
                li.innerHTML = '<div class="img"></div><div class="size">' + size + '</div>';
                $(".img-list").append($(li));
                reader.onload = function() {
                    var result = this.result;
                    var img = new Image();
                    img.src = result;
                    // 如果图片大小小于200kb，则直接上传
                    if (result.length <= 200 * 1024) {
                        img = null;
                        $(li).children('div.img').append('![]('+result+')'); // 预览
                        upload(result, file.type, $(li));  // 直接上传
                        return;
                    }
                    // 图片加载完毕之后进行压缩，然后上传
                    if (img.complete) {
                        callback();
                    } else {
                        img.onload = callback;
                    }
                    function callback() {
                        var data = compress(img); // 使用canvas对大图片进行压缩
                        $(li).children('div.img').append('![]('+data+')'); //预览
                        upload(data, file.type, $(li));  // 上传
                        img = null;
                    }
                };
                reader.readAsDataURL(file);
            })
        };
    </script>
    <script>
        //    使用canvas对大图片进行压缩
        function compress(img) {
            //    用于压缩图片的canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext('2d');
            //    瓦片canvas
            var tCanvas = document.createElement("canvas");
            var tctx = tCanvas.getContext("2d");

            var initSize = img.src.length;
            var width = img.width;
            var height = img.height;
            //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
            var ratio;
            if ((ratio = width * height / 4000000) > 1) {
                ratio = Math.sqrt(ratio);  // 平方根
                width /= ratio;
                height /= ratio;
            } else {
                ratio = 1;
            }
            canvas.width = width;
            canvas.height = height;
            //   铺底色（防止png透明背景转成JPG变黑色）
            ctx.fillStyle = "#fff";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            //  如果图片像素大于100万则使用瓦片绘制
            var count;
            if ((count = width * height / 1000000) > 1) {
                count = ~~(Math.sqrt(count) + 1); // 计算要分成多少块瓦片
                //   计算每块瓦片的宽和高
                var nw = ~~(width / count);    // ~~取整
                var nh = ~~(height / count);
                tCanvas.width = nw;
                tCanvas.height = nh;
                for (var i = 0; i < count; i++) {
                    for (var j = 0; j < count; j++) {
                        //  drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight,destX, destY, destWidth, destHeight)
                        tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                        ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                    }
                }
            } else {
                ctx.drawImage(img, 0, 0, width, height);
            }
            //进行最小压缩（将原来图片的质量压缩到原先的0.1倍）
            var ndata = canvas.toDataURL('image/jpeg', 0.1);
            console.log('压缩前：' + initSize);
            console.log('压缩后：' + ndata.length);
            console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
            tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
            console.log(ndata);
            return ndata;
        }
    </script>
    <script>
        //    图片上传，将base64的图片转成二进制对象，塞进formdata上传
        function upload(basestr, $li) {
            // 将以base64的图片url数据转换为Blob
            var blob = convertBase64UrlToBlob(basestr);
            var pecent = 0, loop = null;
            var xhr = new XMLHttpRequest();
            var formdata = getFormData();
            formdata.append('imagefile', blob);
            xhr.open('post', '/cupload');
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var jsonData = JSON.parse(xhr.responseText);
                    var imagedata = jsonData[0] || {};
                    var text = imagedata.path ? '上传成功' : '上传失败';
                    console.log(text + '：' + imagedata.path);
                    clearInterval(loop);
                    //当收到该消息时上传完毕
                    $li.find(".progress span").animate({'width': "100%"}, pecent < 95 ? 200 : 0, function() {
                        $(this).html(text);
                    });
                    if (!imagedata.path) return;
                    $(".pic-list").append('<a href="' + imagedata.path + '">' + imagedata.name + '（' + imagedata.size + '）![](' + imagedata.path + ')</a>');
                }
            };
            //数据发送进度，前50%展示该进度
            xhr.upload.addEventListener('progress', function(e) {
                if (loop) return;
                pecent = ~~(100 * e.loaded / e.total) / 2;
                $li.find(".progress span").css('width', pecent + "%");
                if (pecent == 50) {
                    mockProgress();
                }
            }, false);
            //数据后50%用模拟进度
            function mockProgress() {
                if (loop) return;
                loop = setInterval(function() {
                    pecent++;
                    $li.find(".progress span").css('width', pecent + "%");
                    if (pecent == 99) {
                        clearInterval(loop);
                    }
                }, 100)
            }
            xhr.send(formdata);
        }
    </script>
</head>
<body>
    <input type="file" id="choose" accept="image/*" multiple onchange="changeImage()">
        <ul class="img-list"></ul>
        <a id="upload">上传图片</a>
    <span class="tips">只允许上传jpg、png及gif</span>
</body>

</html>